package concurrent.blockingQueue;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 内部用PriorityQueue优先队列存储实际元素
 * add/put都是调用offer实现，效果一模一样
 *
 * @author tuyou
 * @date 2020-08-19 23:27:13
 */
public class DelayQueueTest {

	public static void main(String[] args) throws InterruptedException {
		
		DelayQueue<Item> q = new DelayQueue<>();
		for(int i = 0; i < 5; i++){
			Thread.sleep(1000);
			q.put(new Item(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(3)));
		}
		while(!q.isEmpty()){
			System.out.println("take开始");
			Item item = q.take();
			System.out.println("take结束");
			System.out.println(item);
		}
	}
	
	static class Item implements Delayed{

		/**
		 * 延迟到什么时候
		 */
		long delayToTimeStamp;
		
		public Item(long delayToTimeStamp) {
			this.delayToTimeStamp = delayToTimeStamp;
		}

		@Override
		public String toString() {
			return "Item{" +
					"delayToTimeStamp=" + delayToTimeStamp +
					'}';
		}

		@Override
		public int compareTo(Delayed o) {
			Item other = (Item)o;
			return (int) (delayToTimeStamp - other.delayToTimeStamp);
		}

		@Override
		public long getDelay(TimeUnit unit) {
			return TimeUnit.MILLISECONDS.toNanos(delayToTimeStamp - System.currentTimeMillis());
		}
	}
}
